import React, { useState, useEffect } from "react"
import ReactDOM from 'react-dom/client'
import MonacoEditor, { loader } from '@monaco-editor/react'
import { Button, message } from 'antd'

loader.config({ paths: { vs: "/monaco-editor@0.30.1/min/vs" } });

function App() {
  const [menu] = useState(JSON.decode(window.LOW_CODE_MENU))
  const [json, setJSON] = useState('{}')

  const getPostUrl = () => '/api/menu/editor/' + menu.key

  useEffect(()=>{
    setJSON(JSON.toCode(JSON.decode(window.LOW_CODE_SCHEMA)))
  })

  const save = async() => {
    request.post(getPostUrl(), JSON.executeCode(json)).then(function(data) {
      message.success('保存成功')
    }).catch(e=>{
      message.error(e.statusText)
      console.log(e, json)
    })
  }

  const haddleKeyDown = (event) => {
    if(event.key === "s" && (event.ctrlKey || event.metaKey)) {
      save()
      event.preventDefault()
    }
  }

  return (
    <div style={{height:"100vh", overflow:'hidden'}} onKeyDown={haddleKeyDown}>
      <div style={{display:'flex', flexDirection: "column", height:40}}>
        <Button style={{height:'100%'}} type='primary' onClick={save}>保存</Button>
      </div>
      <MonacoEditor defaultValue={'module.exports = \n' + json}
        width='100%' height='calc(100vh - 40px)' 
        onChange={setJSON} 
        onBlur={setJSON} 
        theme="vs-dark" 
        defaultLanguage="javascript" 
        options={{
          selectOnLineNumbers:true,
          "autoIndent": true,
          "formatOnPaste": true,
          "formatOnType": true
        }} 
      />
    </div>
  )
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />)
